'use client';

import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Grid,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Tooltip,
  Divider,
} from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CloseIcon from '@mui/icons-material/Close';
import AutorenewIcon from '@mui/icons-material/Autorenew';
import { styled } from '@mui/material/styles';

// 自定义上传按钮样式
const VisuallyHiddenInput = styled('input')({
  clip: 'rect(0 0 0 0)',
  clipPath: 'inset(50%)',
  height: 1,
  overflow: 'hidden',
  position: 'absolute',
  bottom: 0,
  left: 0,
  whiteSpace: 'nowrap',
  width: 1,
});

interface ResumeSubmitFormProps {
  companyId?: number;
  companyName?: string;
  positionId?: number;
  positionName?: string;
  onClose: () => void;
  onSubmitSuccess?: () => void;
}

const ResumeSubmitForm: React.FC<ResumeSubmitFormProps> = ({
  companyId,
  companyName,
  positionId,
  positionName,
  onClose,
  onSubmitSuccess,
}) => {
  const [formData, setFormData] = useState({
    gender: '',
    phone: '',
    email: '',
    school: '',
    graduation_year: '',
    position_intent: positionName || '',
  });
  
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [userProfile, setUserProfile] = useState<any>(null);
  const [loadingProfile, setLoadingProfile] = useState(false);
  
  // 获取用户个人资料
  useEffect(() => {
    const fetchUserProfile = async () => {
      setLoadingProfile(true);
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('请先登录');
        }
        
        const response = await fetch('/api/profile', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (!response.ok) {
          throw new Error('获取个人资料失败');
        }
        
        const profileData = await response.json();
        setUserProfile(profileData);
        
        // 获取教育经历
        const educationResponse = await fetch('/api/user/education-experiences', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (educationResponse.ok) {
          const educationData = await educationResponse.json();
          if (educationData && educationData.length > 0) {
            // 使用最高学历（假设按创建时间倒序排列）
            const latestEducation = educationData[0];
            
            // 自动填充表单
            setFormData(prev => ({
              ...prev,
              school: latestEducation.school || '',
              graduation_year: latestEducation.end_date ? 
                new Date(latestEducation.end_date).getFullYear().toString() : '',
              gender: profileData.gender || '',
              phone: profileData.phone || '',
              email: profileData.email || '',
            }));
          }
        }
      } catch (err) {
        console.error('获取个人资料失败:', err);
        setError((err as Error).message);
      } finally {
        setLoadingProfile(false);
      }
    };
    
    fetchUserProfile();
  }, []);
  
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  const handleSelectChange = (e: any) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const selectedFile = e.target.files[0];
      
      // 检查文件类型
      const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
      if (!validTypes.includes(selectedFile.type)) {
        setError('请上传PDF或Word格式的文件');
        return;
      }
      
      // 检查文件大小（5MB限制）
      if (selectedFile.size > 5 * 1024 * 1024) {
        setError('文件大小不能超过5MB');
        return;
      }
      
      setFile(selectedFile);
      setError('');
    }
  };
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    try {
      // 验证必填字段
      const requiredFields = ['gender', 'phone', 'email', 'school', 'graduation_year', 'position_intent'];
      const missingFields = requiredFields.filter(field => !formData[field as keyof typeof formData]);
      
      if (missingFields.length > 0) {
        throw new Error('请填写所有必填字段');
      }
      
      if (!file) {
        throw new Error('请上传简历文件');
      }
      
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('请先登录');
      }
      
      // 创建FormData对象
      const submitData = new FormData();
      submitData.append('file', file);
      
      // 添加表单数据
      Object.entries(formData).forEach(([key, value]) => {
        submitData.append(key, value);
      });
      
      // 添加公司和职位信息
      if (companyId) submitData.append('company_id', companyId.toString());
      if (companyName) submitData.append('company_name', companyName);
      if (positionId) submitData.append('position_id', positionId.toString());
      if (positionName) submitData.append('position_name', positionName);
      
      // 发送请求
      const response = await fetch('/api/recruitment/submit-resume', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: submitData
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '提交简历失败');
      }
      
      setSuccess(true);
      
      // 调用成功回调
      if (onSubmitSuccess) {
        setTimeout(() => {
          onSubmitSuccess();
        }, 1500);
      }
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };
  
  const autoFillFromProfile = () => {
    if (!userProfile) return;
    
    setFormData(prev => ({
      ...prev,
      gender: userProfile.gender || prev.gender,
      phone: userProfile.phone || prev.phone,
      email: userProfile.email || prev.email,
    }));
  };
  
  return (
    <Dialog 
      open={true} 
      onClose={onClose}
      maxWidth="md"
      fullWidth
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center',
        borderBottom: '1px solid #eee',
        pb: 2
      }}>
        <Typography variant="h6" component="div">
          简历投递
        </Typography>
        <IconButton onClick={onClose} size="small">
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      
      <DialogContent sx={{ pt: 3 }}>
        <Typography variant="body2" color="text.secondary" paragraph>
          填写以下信息，您的简历将被推送给{companyName || '企业'}。获得面试机会后，我们会通过电话或邮件通知您。
        </Typography>
        
        {loadingProfile && (
          <Box sx={{ display: 'flex', justifyContent: 'center', my: 2 }}>
            <CircularProgress size={24} />
            <Typography variant="body2" color="text.secondary" sx={{ ml: 1 }}>
              正在加载个人资料...
            </Typography>
          </Box>
        )}
        
        {error && (
          <Alert severity="error" sx={{ my: 2 }}>
            {error}
          </Alert>
        )}
        
        {success && (
          <Alert severity="success" sx={{ my: 2 }}>
            简历投递成功！我们会尽快处理您的申请。
          </Alert>
        )}
        
        <Box component="form" onSubmit={handleSubmit} sx={{ mt: 2 }}>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <FormControl fullWidth required>
                <InputLabel id="gender-label">性别</InputLabel>
                <Select
                  labelId="gender-label"
                  name="gender"
                  value={formData.gender}
                  onChange={handleSelectChange}
                  label="性别"
                >
                  <MenuItem value="男">男</MenuItem>
                  <MenuItem value="女">女</MenuItem>
                  <MenuItem value="其他">其他</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="联系电话"
                name="phone"
                value={formData.phone}
                onChange={handleChange}
                required
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="邮箱"
                name="email"
                type="email"
                value={formData.email}
                onChange={handleChange}
                required
              />
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="毕业院校"
                name="school"
                value={formData.school}
                onChange={handleChange}
                required
              />
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="毕业年份"
                name="graduation_year"
                value={formData.graduation_year}
                onChange={handleChange}
                required
                placeholder="例如：2024"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="求职意向"
                name="position_intent"
                value={formData.position_intent}
                onChange={handleChange}
                required
                placeholder="例如：前端开发工程师"
              />
            </Grid>
            
            <Grid item xs={12}>
              <Divider sx={{ my: 1 }} />
              <Box sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'space-between',
                mb: 2
              }}>
                <Typography variant="subtitle2">
                  上传简历文件
                </Typography>
                <Tooltip title="从个人资料自动填充">
                  <Button 
                    startIcon={<AutorenewIcon />} 
                    size="small"
                    onClick={autoFillFromProfile}
                    disabled={!userProfile || loadingProfile}
                  >
                    自动填充
                  </Button>
                </Tooltip>
              </Box>
              
              <Box sx={{ 
                border: '1px dashed #ccc', 
                borderRadius: 1, 
                p: 3, 
                textAlign: 'center',
                bgcolor: '#f9f9f9'
              }}>
                {file ? (
                  <Box>
                    <Typography variant="body2" sx={{ mb: 1 }}>
                      已选择文件: {file.name} ({(file.size / 1024 / 1024).toFixed(2)}MB)
                    </Typography>
                    <Button 
                      variant="outlined" 
                      color="primary"
                      onClick={() => setFile(null)}
                      size="small"
                      startIcon={<CloseIcon />}
                    >
                      移除文件
                    </Button>
                  </Box>
                ) : (
                  <>
                    <Button
                      component="label"
                      variant="contained"
                      startIcon={<CloudUploadIcon />}
                    >
                      上传简历
                      <VisuallyHiddenInput type="file" onChange={handleFileChange} />
                    </Button>
                    <Typography variant="caption" display="block" sx={{ mt: 1 }}>
                      支持PDF、Word格式，文件大小不超过5MB
                    </Typography>
                  </>
                )}
              </Box>
            </Grid>
          </Grid>
        </Box>
      </DialogContent>
      
      <DialogActions sx={{ px: 3, py: 2, borderTop: '1px solid #eee' }}>
        <Button onClick={onClose} disabled={loading}>
          取消
        </Button>
        <Button 
          variant="contained" 
          color="primary" 
          onClick={handleSubmit}
          disabled={loading || success}
          startIcon={loading && <CircularProgress size={20} />}
        >
          {loading ? '提交中...' : '提交'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ResumeSubmitForm;
